/**
 * @description 这里主要是主wifi 和 访客wifi的一些通用逻辑
 */
import { getByteLength } from '@/utils/common';
import { errorCode, wifiModeDict, LOCAL_KEY } from '@/constant/dict';
export default {
    data() {
        let nameCheck = (rule, value, callback) => {
            if (!value) {
                callback(new Error(this.$t('errorTips.cannotBeEmpty')));
            } else if (getByteLength(value) > 32) {
                //输入长度超标的提示
                callback(new Error(this.$t('errorTips.maxLength')));
            } else {
                callback();
            }
        };

        const pwdCheck = (rule, value, callback) => {
            const result = this.$checkStr(value, false, false, true, false, 64, 32, 126, 8);
            if (!value) {
                callback(new Error(this.$t('errorTips.cannotBeEmpty')));
            } else if (result == errorCode.BYTEERR) {
                callback(new Error(this.$t('netWork.wifiSettings.msg_wifi_5')));
            } else if (result == errorCode.STRERR || result == errorCode.ACCIIERR) {
                callback(new Error(this.$t('netWork.wanSettings.illegalDataTitle')));
            } else {
                callback();
            }
        };
        return {
            wifiModeDict: wifiModeDict,
            wifiModeType: wifiModeDict.WIFI24,
            wifiSwitchValue: false,
            wifiSwitchValue_5G: false,
            wifiSwitchValue_6G: false,
            passwordVisibleFlag: false,
            passwordVisible: 'password',
            icon: 'el-icon-my-eye-hide',
            wifiNameBytes: 0,
            wifiNameLength: 32,
            wifiNameBytes_5G: 0,
            wifiNameLength_5G: 32,
            wifiNameBytes_6G: 0,
            wifiNameLength_6G: 32,
            wifiSettingRules: {
                wifiName: [
                    { required: true, trigger: 'blur', message: this.$t('errorTips.cannotBeEmpty') },
                    { validator: nameCheck, trigger: 'blur' }
                ],
                wifiName_5G: [
                    { required: true, trigger: 'blur', message: this.$t('errorTips.cannotBeEmpty') },
                    { validator: nameCheck, trigger: 'blur' }
                ],
                wifiPassword: [
                    { required: true, trigger: 'blur', message: this.$t('errorTips.cannotBeEmpty') },
                    { validator: pwdCheck, trigger: 'blur' }
                ],
                wifiPassword_5G: [
                    { required: true, trigger: 'blur', message: this.$t('errorTips.cannotBeEmpty') },
                    { validator: pwdCheck, trigger: 'blur' }
                ]
            },
            supportWifiArr: JSON.parse(localStorage.getItem(LOCAL_KEY.WIFI_TYPE)) || [true, true, false]
        };
    },
    watch: {
        'wifiSettingForm.wifiName': {
            handler(nVal) {
                if (nVal) {
                    this.wifiNameBytes = getByteLength(nVal);
                    this.wifiNameLength = this.wifiNameBytes >= 32 ? nVal.length : 32;
                } else {
                    this.wifiNameBytes = 0;
                }
            }
        },

        'wifiSettingForm.wifiName_5G': {
            handler(nVal) {
                if (nVal) {
                    this.wifiNameBytes_5G = getByteLength(nVal);
                    this.wifiNameLength_5G = this.wifiNameBytes_5G >= 32 ? nVal.length : 32;
                } else {
                    this.wifiNameBytes_5G = 0;
                }
            }
        },
        'wifiConfig_6G.wifiName': {
            handler(nVal) {
                if (nVal) {
                    this.wifiNameBytes_6G = getByteLength(nVal);
                    this.wifiNameLength_6G = this.wifiNameBytes_6G >= 32 ? nVal.length : 32;
                } else {
                    this.wifiNameBytes_6G = 0;
                }
            }
        },

        'wifiSettingForm.broadcastValue': {
            handler(newVal) {
                if ('none' == this.macRestrictMode || this.$store.state.platformType == 'IPQ') {
                    if (newVal === '1') {
                        this.$nextTick(() => {
                            this.wifiSettingForm.wpsConnectionValue = '0';
                            this.wifiSettingForm.wpsConnectionDisabled = true;
                        });
                    } else {
                        this.wifiSettingForm.wpsConnectionDisabled = false;
                    }
                }
            }
        },

        'wifiSettingForm.broadcastValue_5G': {
            handler(newVal) {
                if ('none' == this.macRestrictMode_5G || this.$store.state.platformType == 'IPQ') {
                    if (newVal === '1') {
                        this.$nextTick(() => {
                            this.wifiSettingForm.wpsConnectionValue_5G = '0';
                            this.wifiSettingForm.wpsConnectionDisabled_5G = true;
                        });
                    } else {
                        this.wifiSettingForm.wpsConnectionDisabled_5G = false;
                    }
                }
            }
        }
    },
    computed: {
        isWifi24() {
            return this.wifiModeType === wifiModeDict.WIFI24;
        },

        isWifi5() {
            return this.wifiModeType === wifiModeDict.WIFI5;
        },

        isWifi6() {
            return this.wifiModeType === wifiModeDict.WIFI6;
        },

        // get current wifi status is open or close
        getWifiIsOpenOrClose() {
            return (this.wifiSwitchValue && this.isWifi24) || (this.wifiSwitchValue_5G && this.isWifi5) || (this.wifiSwitchValue_6G && this.isWifi6);
        },

        /**
         * 隐藏 Tab ，只支持一种 WIFI
         * @returns Boolean
         */
        isHideTab() {
            return this.supportWifiArr.filter((item) => item === true).length === 1;
        },

        /**
         * 支持2种 WIFI 模式
         * @returns Boolean
         */
        isShowTwoTab() {
            return this.supportWifiArr.filter((item) => item === true).length === 2;
        },

        /**
         * 支持所有 WIFI 模式
         * @returns Boolean
         */
        isShowAllTab() {
            return this.supportWifiArr.every(Boolean);
        }
    },
    created() {},
    methods: {
        /**
         * @description get channelWidthLabel
         */
        getChannelWidthLabel(options, value) {
            if (Array.isArray(options) && options.length) {
                const currentChannel = options.find((item) => item.value === value);
                return currentChannel ? currentChannel.label : value;
            } else {
                return value;
            }
        },
        /**
         * @description change form password display status
         */
        showPass() {
            if (this.passwordVisible === 'text') {
                this.passwordVisible = 'password';
                //refresh iamge
                this.icon = 'el-icon-my-eye-hide';
            } else {
                this.passwordVisible = 'text';
                this.icon = 'el-icon-my-eye-reveal';
            }
        },

        /**
         * @description 校验wifi名特殊字符
         * @param {*} val
         * @returns Boolean
         */
        isValidNameString(val) {
            var len = val.length;
            for (let i = 0; i < len; i++) {
                if (val.charAt(i) > '~' || val.charAt(i) < ' ') {
                    return false;
                }
            }
            return true;
        },

        /**
         * @description 获取Select中选中的label
         */
        formatSelectLabel(list, current) {
            const pair = list.find((item) => item.value === current);
            return pair ? pair.label : current;
        },

        /**
         * @description 加密方式数据处理
         * @param {*} json
         * @returns Array
         */
        getSecurityType(json) {
            try {
                return Object.entries(JSON.parse(json)).map(([key, value]) => ({
                    value: key,
                    label: value
                }));
            } catch (error) {
                console.error('SECURITY TYPE JSON ERR =>', error);
                return [];
            }
        },

        /**
         * @description 切换 tab wifi mode
         * @param {String} _mode 2.4G / 5G / 6G
         */
        switchWifiMode(_mode) {
            this.wifiModeType = _mode;
            this.passwordVisibleFlag = false;
            this.passwordVisible = 'password';
            this.icon = 'el-icon-my-eye-hide';
        },

        /**
         * @description 修改隐私协议的时候，如果选中 open（none），就隐藏密码框
         */
        changeSecurityType() {
            switch (this.wifiModeType) {
                case wifiModeDict.WIFI5:
                    if (this.wifiSettingForm.securityTypeValue_5G == 'none') {
                        this.wifiSettingForm.wifiPasswordShow_5G = false;
                    } else {
                        this.wifiSettingForm.wifiPasswordShow_5G = true;
                    }
                    break;
                case wifiModeDict.WIFI6:
                    if (this.wifiConfig_6G.securityTypeValue == 'none') {
                        this.wifiConfig_6G.wifiPasswordShow = false;
                    } else {
                        this.wifiConfig_6G.wifiPasswordShow = true;
                    }
                    break;
                default:
                    if (this.wifiSettingForm.securityTypeValue == 'none') {
                        this.wifiSettingForm.wifiPasswordShow = false;
                    } else {
                        this.wifiSettingForm.wifiPasswordShow = true;
                    }
                    break;
            }
        },

        /**
         * @description 点击编辑按钮，打开对应编辑模式
         */
        changeEditStatus() {
            switch (this.wifiModeType) {
                case wifiModeDict.WIFI5:
                    this.wifiSettingForm.edit_5G = !this.wifiSettingForm.edit_5G;
                    break;
                case wifiModeDict.WIFI6:
                    this.wifiConfig_6G.edit = !this.wifiConfig_6G.edit;
                    break;
                default:
                    this.wifiSettingForm.edit = !this.wifiSettingForm.edit;
                    break;
            }
        },

        /**
         * @description 更改wifi状态
         */
        changeWifiStatus() {
            if (this.getWifiIsOpenOrClose) {
                this.$refs.openWifiRef.show();
            } else {
                this.$refs.closeWifiRef.show();
            }
        },

        /**
         * @description 更改密码是否可见状态
         */
        changePWDisplayStatus() {
            this.passwordVisibleFlag = !this.passwordVisibleFlag;
        },

        /**
         * @description 点击保存，触发表单校验
         */
        checkBeforeSave() {
            this.$refs.wifiSettingForm.validate((valid) => {
                if (valid) {
                    //pass
                    this.$refs.saveDialogRef.show();
                }
            });
        },

        /**
         * @description 点击退出，初始化数据
         */
        onCancel() {
            this.wifiSettingForm.edit = false;
            this.wifiSettingForm.edit_5G = false;
            this.wifiConfig_6G.edit = false;
            this.passwordVisible = 'password';
            //refresh iamge
            this.icon = 'el-icon-my-eye-hide';
            this.$refs.saveDialogRef.hide();
            
            if (this.onLoad) {
                this.onLoad();
            }
            if (this.init) {
                this.init();
            }
        },

        /**
         * @description 跳转页面
         * @param {*} _type
         * @param {*} query
         */
        jumpUrl(_type, query) {
            this.$router.replace({
                path: _type,
                query
            });
        }
    }
};
